package com.kl.websocket.customAppender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.kl.websocket.LoggerDisruptorQueue;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lck
 * @date 2020/10/20 15:02
 * @description
 */
public class MyAppender extends AppenderBase<ILoggingEvent> {

	/**
	 * 添加日志
	 * @param iLoggingEvent
	 */
	@Override
	protected void append(ILoggingEvent iLoggingEvent) {
//			webSocketServer.sendMessage(doLayout(iLoggingEvent));
		/** SimpMessagingTemplate 是 spring websocket下的包，可以发送信息到前端 */
		LoggerDisruptorQueue.publishEvent(doLayout(iLoggingEvent));
	}

	/**
	 * 格式化日志
	 * @param event
	 * @return
	 */
	public String doLayout(ILoggingEvent event) {
		StringBuilder sbuf = new StringBuilder();
		if (null != event && null != event.getMDCPropertyMap()) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

			sbuf.append(simpleDateFormat.format(new Date(event.getTimeStamp())));
			sbuf.append("\t");

			sbuf.append(event.getLevel());
			sbuf.append("\t");

			sbuf.append(event.getThreadName());
			sbuf.append("\t");

			sbuf.append(event.getLoggerName());
			sbuf.append("\t");

			sbuf.append(event.getFormattedMessage().replace("\"", "\\\""));
			sbuf.append("\t");
		}

		return sbuf.toString();
	}
}
